<template>
  <div>
    <div class="search">
      <input type="text" class="search-input" placeholder="请输入城市/景点" v-model="keyword">
    </div>
    <div class="search-content" v-show="keyword" ref="serach">
      <ul>
        <li
          v-for="item in this.list"
          :key="item.id"
          class="search-item border-bottom"
          @click="handleCityClick(item.name)"
        >
          {{item.name}}
        </li>
        <li v-show="hasNoData" class="search-item border-bottom">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>
<script>
import BScroll from 'better-scroll'
import {mapMutations} from 'vuex'
export default {
  name: 'Searchfc',
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  props: {
    cities: Object
  },
  methods: {
    handleCityClick (city) {
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.serach)
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((element) => {
            if (element.spell.indexOf(this.keyword) > -1 ||
                element.name.indexOf(this.keyword) > -1) {
              result.push(element)
            }
          })
        }
        this.list = result
      }, 100)
    }
  }
}
</script>
<style lang="stylus" scoped>
@import '~styles/varibles'
.search
  background $bgColor
  padding .1rem
  .search-input
    width 100%
    line-height .6rem
    padding 0 .1rem
    text-align center
    box-sizing border-box
    color #333
    font-size .32rem
.search-content
  position absolute
  top 1.66rem
  left 0
  right 0
  bottom 0
  background #fff
  z-index 1
  overflow hidden
  .search-item
    line-height .62rem
    padding-left .2rem
    color #333
</style>
